from fastapi import APIRouter, status

from core.exceptions import NormalException
from schemas.base import R
from schemas.network import ConnectToWiFi, UpdateNetwork
from utils.network import connectWiFi, getNetworkInfo, getWiFi, rescanWiFi, updateNetworkInfo

router = APIRouter(prefix="/network", tags=["网络配置接口"])


@router.get(
    "/list/",
    summary="获取网络信息列表"
)
def getNetworkList():
    infos = getNetworkInfo()
    return R(data=infos)


@router.put(
    "/",
    summary="修改网络信息"
)
def updateNetwork(data: UpdateNetwork):
    print(data)
    items = data.netmask.split(".")
    mask = 0
    for item in items:
        _b = bin(int(item))
        mask += _b.count("1")
    address = data.address + "/" + str(mask)
    updateNetworkInfo(name=data.name, options={
        "ipv4.method": data.method,
        "ipv4.addresses": address,
        "ipv4.gateway": data.gateway,
        "ipv4.dns": data.dns
    })
    return R()


@router.get(
    "/wifi/list/",
    summary="获取当前可用的wifi列表"
)
def getWiFiList():
    return R(data=getWiFi())


@router.post(
    "/wifi/connect/",
    summary="连接指定wifi"
)
def connectToTargetWiFi(data: ConnectToWiFi):
    res = connectWiFi(data.ssid, data.password)
    if res:
        return R()
    else:
        raise NormalException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="网络连接失败，请检查密码后重试"
        )


@router.post(
    "/wifi/rescan/",
    summary="重新扫描可用wifi列表"
)
def rescanWiFiList():
    rescanWiFi()
    return R()